import { getStore, setStore, removeStore } from '@/utils/store'
import {
  login,
  logout,
  getUserInfo,
  getRouters,
  refreshToken
} from '@/api/user'
import Cookies from 'js-cookie'
import {
  getToken,
  setToken,
  setRefreshTtoken,
  setExpiresIn,
  removeToken,
  removeRefreshToken,
  removeExpiresIn,
  removeUserInfo
} from '@/utils/auth'
// 加密处理
import { encryption } from '@/utils/utils'
import router, { resetRouter } from '@/router'

const state = {
  // token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  userInfo: {},
  permissions: {},
  // refresh_token: "",
  // expires_in: ""
  menu:
    getStore({
      name: 'menu'
    }) || [],
  menuAll: [],
  expires_in:
    getStore({
      name: 'expires_in'
    }) || '',
  access_token: Cookies.get('access_token') || '',
  refresh_token:
    getStore({
      name: 'refresh_token'
    }) || ''
}

const mutations = {
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },

  SET_ACCESS_TOKEN: (state, access_token) => {
    state.access_token = access_token
    Cookies.set('access_token', access_token)
  },
  SET_EXPIRES_IN: (state, expires_in) => {
    state.expires_in = expires_in
    setStore({
      name: 'expires_in',
      content: state.expires_in,
      type: 'session'
    })
  },
  SET_REFRESH_TOKEN: (state, rfToken) => {
    state.refresh_token = rfToken
    setStore({
      name: 'refresh_token',
      content: state.refresh_token,
      type: 'session'
    })
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
    Cookies.set('UserInfo', userInfo)
  },

  SET_MENU: (state, menu) => {
    state.menu = menu
    setStore({
      name: 'menu',
      content: state.menu,
      type: 'session'
    })
  },
  SET_MENU_ALL: (state, menuAll) => {
    state.menuAll = menuAll
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    const list = {}
    for (let i = 0; i < permissions.length; i++) {
      list[permissions[i]] = true
    }
    state.permissions = list
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    // console.log(userInfo)
    const user = encryption({
      data: userInfo,
      key: 'tbyf@healthcloud',
      param: ['password']
    })
    // commit("SET_ACCESS_TOKEN", "770aa846-5e95-4de4-8b1e-8aba7a6bc5ea")
    return new Promise((resolve, reject) => {
      login(user.username, user.password)
        .then(response => {
          const data = response
          const userData = {
            sysOrganizationId: data.sys_organization_id,
            userId: data.user_id,
            userName: data.username
          }
          window.sessionStorage.setItem('userInfo', JSON.stringify(userData))

          commit('SET_ACCESS_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          commit('SET_EXPIRES_IN', data.expires_in)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 刷新token
  RefreshToken({ commit, state }) {
    return new Promise((resolve, reject) => {
      refreshToken(state.refresh_token)
        .then(response => {
          console.log(response)
          const data = response
          commit('SET_ACCESS_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          commit('SET_EXPIRES_IN', data.expires_in)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // 获取权限信息
  getUserInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then(res => {
          // console.log(res)
          const data = res.data
          window.sessionStorage.setItem('user', JSON.stringify(data))
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // 获取路由信息
  getRouters({ commit }) {
    return new Promise((resolve, reject) => {
      getRouters()
        .then(response => {
          const { data } = response
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // 用户登出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(res => {
          console.log(res)
          commit('SET_ACCESS_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_REFRESH_TOKEN', '')
          commit('SET_EXPIRES_IN', '')
          window.sessionStorage.removeItem('user')
          window.sessionStorage.removeItem('userInfo')
          removeToken()
          removeUserInfo()
          resetRouter()
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // login({ commit }, userInfo) {
  //   return new Promise((resolve, reject) => {
  //     const data = { token: "admin-token" }
  //     console.log(data)
  //     commit("SET_TOKEN", data.token)
  //     setToken(data.token)
  //     resolve()
  //   })
  // },
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const data = {
        roles: ['admin'],
        introduction: '我是超级管理员',
        avatar:
          'https://img.zcool.cn/community/01d54e5b4870e6a8012036be67cf4d.gif',
        name: 'Super Admin'
      }
      if (!data) {
        reject('验证失败，请再次登录.')
      }
      const { roles, name, avatar, introduction } = data

      // 角色必须是非空数组
      if (!roles || roles.length <= 0) {
        reject('getInfo: 角色必须是非空数组!')
      }

      commit('SET_ROLES', roles)
      commit('SET_NAME', name)
      commit('SET_AVATAR', avatar)
      commit('SET_INTRODUCTION', introduction)
      resolve(data)
    })
  },
  // logout({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     commit("SET_ACCESS_TOKEN", "")
  //     commit("SET_ROLES", [])
  //     commit("SET_REFRESH_TOKEN", "")
  //     commit("SET_EXPIRES_IN", "")
  //     window.sessionStorage.removeItem("user")
  //     window.sessionStorage.removeItem("userInfo")
  //     removeToken()
  //     removeUserInfo()
  //     resetRouter()
  //     resolve()
  //   })
  // },

  // 删除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      removeRefreshToken()
      removeExpiresIn()
      resolve()
    })
  },
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // 根据角色生成可访问的 roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {
      root: true
    })
    // 动态添加可访问的roles
    router.addRoutes(accessRoutes)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
